package com.falcon.web.auto;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.swan.security.auto.config.SecurityConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 1.本配置类只配置业务的缓存管理器
 * 2.Cache 公共配置类和启用参考 CacheAutoConfig,
 */
@Slf4j
@Configuration
public class WebCacheConfig {

    @Bean
    public CacheManager tokenCacheManager(SecurityConfig securityConfig) {
        SecurityConfig.TokenConfig tokenConfig = securityConfig.getToken();
        // 默认两小时
        Long ttlMs = Objects.nonNull(tokenConfig.getTtl()) ? tokenConfig.getTtl() : 2 * 60 * 60 * 1000L;

        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCaffeine(Caffeine.newBuilder()
                .expireAfterWrite(ttlMs, TimeUnit.MICROSECONDS)
                .maximumSize(Integer.MAX_VALUE));
        return cacheManager;
    }

}
